package algorithm.leetcode.medium;

/*
 给定一个链表和一个特定值 x，对链表进行分隔，使得所有小于 x 的节点都在大于或等于 x 的节点之前。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/12/25
 */
public class Question86 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(4);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(2);
        Question86 question = new Question86();
        ListNode partition = question.partition(head, 3);
        System.out.println(partition);
    }

    public ListNode partition(ListNode head, int x) {
        ListNode beforeHead = new ListNode(0);
        ListNode afterHead = new ListNode(0);

        ListNode beforeTemp = beforeHead;
        ListNode afterTemp = afterHead;

        while (head != null) {
            if (head.val < x) {
                beforeTemp.next = head;
                beforeTemp = beforeTemp.next;
            }else {
                afterTemp.next = head;
                afterTemp = afterTemp.next;
            }
            head = head.next;
        }
        /*
        比如【1，3，5，6，2】这个链表，假设 x=3，则可得到两个链表分别是【1，2】和【3，5，6】，
        但此时右链表的尾部，即6的尾部仍指向2，如果不把右链表的尾部置为None，
        最后就会得到 1->2->3->5->6->2 这个链表，在节点2处成环。
        因此必须将右链表尾部手动置为None，实现断链
         */
        afterTemp.next = null;
        beforeTemp.next = afterHead.next;
        return beforeHead.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
